#include "marqueewidget.h"
#include <QPainter>

MarqueeWidget::MarqueeWidget(QWidget *parent)
    : QWidget(parent),
      currentIndex(0),
      offset(0),
      scrollSpeed(2),
      stayDuration(3000)  // 默认停留 3 秒
{
    font.setPixelSize(32);

    animationTimer = new QTimer(this);
    connect(animationTimer, &QTimer::timeout, this, &MarqueeWidget::onAnimationFrame);
    animationTimer->start(30);  // 启动动画定时器

    stayTimer = new QTimer(this);
    connect(stayTimer, &QTimer::timeout, this, &MarqueeWidget::onStayTimeout);
}

void MarqueeWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    QPen pen(QColor(109, 109, 109));
    painter.setPen(pen);
    painter.setFont(font);

    if (textList.isEmpty()) return;

    QString currentText = textList[currentIndex];

    // 获取文本宽度
    QFontMetrics fm(font);
    int textWidth = fm.horizontalAdvance(currentText);

    // 绘制文本
    QRect rect;

    if (animationTimer->isActive()) {
        // 滚动阶段：从右向左
        rect = QRect(offset, 0, textWidth, height());
    } else {
        // 停留阶段：居中显示
        int centerX = (width() - textWidth) / 2;
        rect = QRect(centerX, 0, textWidth, height());
    }

    painter.drawText(rect, Qt::AlignVCenter | Qt::AlignLeft, currentText);
}


void MarqueeWidget::onAnimationFrame()
{
    offset -= scrollSpeed;

    // 判断是否滚动到位（文本完全显示）
    QFontMetrics fm(font);
    int textWidth = fm.horizontalAdvance(textList[currentIndex]);

    if (offset + textWidth <= width()) {
        // 停止动画，设置居中偏移量
        animationTimer->stop();

        // 计算居中偏移量
        offset = (width() - textWidth) / 2;

        // 启动停留计时器
        stayTimer->start(stayDuration);
    }

    update();
}

void MarqueeWidget::onStayTimeout()
{
    stayTimer->stop();

    // 更新当前索引
    currentIndex = (currentIndex + 1) % textList.size();

    // 重置偏移量（从右侧开始滚动）
    offset = width();

    // 启动下一轮动画
    animationTimer->start(30);
}

void MarqueeWidget::setTexts(const QStringList &texts)
{
    textList = texts;
    currentIndex = 0;
    offset = width();  // 初始化偏移量
    update();  // 触发重绘
}


